package com.wangsh.webforward.common.util;

import java.util.HashMap;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;


/**
 * jsoup的工具类
 * @author TeaBig
 */
public class JsoupUtil
{
	/* httpUtil */
	protected HttpUtil httpUtil =new HttpUtil(); 
	
	/**
	 * 解析Html
	 * @return
	 */
	public JSONObject faceBookHead(String html)
	{
		JSONObject resultJSON = new JSONObject();
		/* 解析Html */
		Document document = Jsoup.parse(html);
		/*--获取数据--*/
		return resultJSON ; 
	}
	
	/**
	 * ip
	 * 先查询淘宝,如果查询不到,再查询ip138
	 * 如果查询的是本地国家,要重新查询本地ip,获取国家
	 * @return 返回值是一个json;
{
	"code":"0",
	"info":"",
	"data":
	{
	}
}
	 */
	public JSONObject ipLocation(String ip,Map<String,String> headerReqMap)
	{
		JSONObject responseJSON = new JSONObject() ; 
		/* 这个是返回结果 */
		String response = "" ; 
		/* 查询淘宝 */
		response = this.taobao(ip, headerReqMap);
		/* 解析JSON字符串 */
		responseJSON = (JSONObject) JSON.parse(response);
		if(responseJSON != null && "0".equalsIgnoreCase(responseJSON.get("code") + ""))
		{
			/* 查询出结果 */
			JSONObject dataResJSON = (JSONObject) responseJSON.get("data");
			String city_id = dataResJSON.getString("city_id");
			String county_id = dataResJSON.getString("county_id");
			if("local".equalsIgnoreCase(city_id) || "local".equalsIgnoreCase(county_id))
			{
				/* 说明是内网ip,再查询一下本地的ip */
				/* 查询淘宝 */
				response = this.taobao("", headerReqMap);
				responseJSON = (JSONObject) JSON.parse(response);
			}
		}else
		{
			/* 查询ip138 */
			response = this.ip138(ip);
			/* 解析json数据 */
			responseJSON = (JSONObject) JSON.parse(response);
		}
		return responseJSON; 
	}
	
	/**
	 * 淘宝的测试ip
	 * 如果返回的json中,county_id为local,表示本机,
	 * 单独查询本机的ip,为国家赋值
	 * @return
	 */
	public String taobao(String ip,Map<String,String> headerReqMap)
	{
		if(ip == null || "".equalsIgnoreCase(ip))
		{
			ip = "myip";
		}
		String urlStr = ConstatFinalUtil.CONFIG_JSON.getString("ip.url");
		/* 请求头 */
		Map<String, String> headerMap = new HashMap<String, String>();
		if(headerReqMap.isEmpty())
		{					             
			headerMap.put("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
		}else
		{
			headerMap.putAll(headerReqMap);
		}
		/* 请求体 */
		Map<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("ip", ip);
		/* 响应体 */
		Map<String, String> responseMap = new HashMap<String, String>();
		/* post请求 */
		String response = this.httpUtil.methodGet(urlStr, headerMap, paramsMap, responseMap);
		/* 增加一个统一描述的字符串 */
		JSONObject responseJSON = (JSONObject) JSON.parse(response);
		if(responseJSON != null && "0".equalsIgnoreCase(responseJSON.get("code") + ""))
		{
			JSONObject dataReqJSON = responseJSON.getJSONObject("data");
			String allInfo = dataReqJSON.getString("country") + " " + dataReqJSON.getString("region") + " " + dataReqJSON.getString("city") 
					+ " " + dataReqJSON.getString("isp") ; 
			dataReqJSON.put("allInfo", allInfo);
			return responseJSON.toJSONString(); 
		}
		return "" ; 
	}
	 
	/**
	 * 如果查询的是本机ip;ip为空字符串,请求的地址是:http://www.ip138.com/ips138.asp?ip=123.53.38.240&action=2
	 * 如果是指定ip,请求的地址是:http://www.ip138.com/
	 * @param ip
	 * @return
		本机:[123.53.36.106] 来自：河南省安阳市 电信
		指定Ip:美国 俄勒冈 波特兰
	 */
	public String ip138(String ip)
	{
		JSONObject resultJSON = new JSONObject();
		JSONObject dataResultJSON = new JSONObject();
		/* 如果查询的是本机ip */
		if("myip".equalsIgnoreCase(ip))
		{
			ip = "" ; 
		}
		String charset = "gbk" ; 
		String ipResult = "";
		try
		{
			// 请求头
			Map<String, String> headerMap = new HashMap<String, String>();
			// 请求体
			Map<String, String> paramsMap = new HashMap<String, String>();
			// 响应头 响应体是网页给的
			Map<String, String> responseMap = new HashMap<String, String>();
			headerMap.put("User-Agent",
					"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36");
			String urlStr = "" ; 
			String response = ""; 
			/* 如果ip要是为空,查看本机ip */
			if(ip == null || "".equalsIgnoreCase(ip))
			{
				urlStr = "http://2000019.ip138.com/" ; 
				paramsMap.clear();
				responseMap.clear();
				response = httpUtil.methodGet(urlStr, headerMap, paramsMap, responseMap);
				
				/* 解析对象 */
				Document document = Jsoup.parse(response);
				Elements pInfoList = document.getElementsByTag("p");
				if(pInfoList.size() > 0 )
				{
					/* 存储的有ip和其它信息 */
					Element pInfo = pInfoList.get(0);
					String ipStrText = pInfo.text().trim() ; 
					ip = ipStrText.substring(ipStrText.indexOf("[") + 1, ipStrText.indexOf("]"));
					/* 查询ip归属地 */
					String indexStr = "来自："; 
					ipResult = ipStrText.substring(ipStrText.indexOf(indexStr) + indexStr.length());
				}
			}else
			{
				/* 有ip,查看ip */
				urlStr = ConstatFinalUtil.CONFIG_JSON.getString("ip.138.url");
				paramsMap.put("ip", ip);
				paramsMap.put("action", "2");
				headerMap.put("Content-Type", "text/html;charset=" + charset);
				response = httpUtil.methodGet(urlStr, headerMap, paramsMap, responseMap,charset);
				Document document = Jsoup.parse(response);
				
				// 获取 这个标签的唯一表示, 是class的属性值为ul1
				Elements elementsByClass = document.getElementsByClass("ul1");
				// 获取到所有li标签的内容
				Elements elementsByTag = elementsByClass.first().getElementsByTag("li");
				Element firstLi = elementsByTag.first();
				String li = firstLi.text().trim();
				String[] split = li.split("：");
				ipResult = null;
				if(split.length == 2)
				{
					ipResult = split[1];
				}
			}
			/* 根据ipResult存储json中data部分 */
			if(ipResult != null && !"".equalsIgnoreCase(ipResult))
			{
				/* 第一个字符串是国家
				 * 后面的原样保留 */
				String[] ipResults = ipResult.split(" ");
				dataResultJSON.put("country", ipResults[0]);
				dataResultJSON.put("country_id", "");
				
				dataResultJSON.put("allInfo", ipResult);
				
				dataResultJSON.put("ip", ip);
			}
			/* 存储数据 */
			resultJSON.put("data", dataResultJSON);
			/* 成功 */
			resultJSON.put("code", "0");
		} catch (Exception e)
		{
			ConstatFinalUtil.SYS_LOGGER.error("解析ip138出错了,ip:{}", ip, e);
			resultJSON.put("code", "-1");
		}
		return resultJSON.toJSONString();
	}
}
